﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BasicForms;
using CustomSecurity;
using System.Data.SqlClient;
namespace ListForms
{
    public partial class FrmEditFunction : FrmBaseEditForm
    {
        Function function;
        public delegate void OnRequestChangeDataSource();
        public event OnRequestChangeDataSource RequestChangedDataSource;

        public FrmEditFunction(int functionID)
        {
            InitializeComponent();
            function = FunctionList.GetByID(functionID);
            if (function == null)
            {
                FunctionList.All.LoadFromDB();
                function = FunctionList.GetByID(functionID);
            }
            if (function != null)
            {
                lbFunctionName.Text = "Function Name: " + function.Name;
                lbDescription.Text = "Description: " + function.Description;
            }
            gridDoiTuong.DataSource = CallFunctionList.GetByFunctionID(functionID).DefaultView;
            gridDoiTuong.KeyUp += new KeyEventHandler(gridDoiTuong_KeyUp);
            ((DataView)gridDoiTuong.DataSource).Table.TableNewRow += new DataTableNewRowEventHandler(Table_TableNewRow);
        }

        void Table_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            try
            {
                if (((DataTable)sender).DefaultView.Count > 0)
                {
                    foreach (DataColumn dtCol in ((DataTable)sender).Columns)
                    {
                        if (dtCol.ColumnName != "ID")
                        {
                            e.Row[dtCol.ColumnName] = ((DataTable)sender).DefaultView[((DataTable)sender).DefaultView.Count - 1][dtCol.ColumnName];
                        }
                    }
                }
            }
            catch { }
        }

        void gridDoiTuong_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                Delete();
            }
        }

        private object GetValue(object value)
        {
            if (value is string)
                if (string.IsNullOrEmpty((string)value)) return DBNull.Value;
            return value;
        }
        protected override void SaveAndClose()
        {
            try
            {
                CheckFullInfo();

                int rowAffected = 0;
                using (SqlConnection conn = new SqlConnection(GeneralLibs.LocalSettings.ConnectString))
                {
                    conn.Open();
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        try
                        {
                            cmd.Transaction = conn.BeginTransaction(IsolationLevel.ReadUncommitted);
                            foreach (DataRow row in ((DataView)gridDoiTuong.DataSource).Table.Rows)
                            {
                                cmd.Parameters.Clear();
                                if (row.RowState == DataRowState.Unchanged) continue;
                                else if (row.RowState == DataRowState.Added)
                                {
                                    cmd.CommandText = "INSERT INTO [CallFunction](FunctionID, DllName, FormName) \n" +
                                                      "Values(@FunctionID, @DllName, @FormName)";
                                    cmd.Parameters.AddRange(new SqlParameter[] { 
                                                                                    new SqlParameter("@FunctionID", function.FunctionID), 
                                                                                    new SqlParameter("@DllName", GetValue(row["DllName"])),
                                                                                    new SqlParameter("@FormName", GetValue(row["FormName"]))
                                                                                });
                                }
                                else if (row.RowState == DataRowState.Modified)
                                {
                                    cmd.CommandText = "UPDATE [CallFunction] SET DllName = @DllName, FormName = @FormName\n" +
                                                      "WHERE ID = @ID";
                                    cmd.Parameters.AddRange(new SqlParameter[] 
                                                                            {   
                                                                                new SqlParameter("@ID", row["ID"]), 
                                                                                new SqlParameter("@DllName", GetValue(row["DllName"])),
                                                                                new SqlParameter("@FormName", GetValue(row["FormName"]))
                                                                            });
                                }
                                else if (row.RowState == DataRowState.Deleted)
                                {
                                    row.RejectChanges();
                                    cmd.CommandText = "DELETE FROM [CallFunction] WHERE ID = " + row["ID"];
                                    row.Delete();
                                }
                                rowAffected += cmd.ExecuteNonQuery();
                            }
                            cmd.Transaction.Commit();
                            ((DataView)gridDoiTuong.DataSource).Table.AcceptChanges();
                        }
                        catch (Exception e)
                        {
                            BasicForms.FrmWarning.Show(e.Message);
                            cmd.Transaction.Rollback();
                            ((DataView)gridDoiTuong.DataSource).Table.RejectChanges();
                            rowAffected = 0;
                        }
                    }
                }
                _EditState = EditState.Saved;
                if (rowAffected > 0)
                {
                    CallFunctionList.All.LoadFromDB();
                    if (RequestChangedDataSource != null) RequestChangedDataSource();
                }
                this.Close();
            }
            catch(Exception ex)
            {
                BasicForms.FrmWarning.Show(ex.Message);
            }
        }

        private void Delete()
        {
            DataRow deletedRow = gridViewDoiTuong.GetFocusedDataRow();
            if (deletedRow != null)
            {
                if (!deletedRow.IsNull("ID"))
                {
                    if (MessageBox.Show("Are you sure delete?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        deletedRow.Delete();
                    }
                }
                else
                    ((DataView)gridViewDoiTuong.DataSource).Table.Rows.Remove(deletedRow);
            }
        }
    }
}
